﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Permission.Models;

namespace Microhard.Permission.MVCFilter
{
    public class MVCFilterAtrForLogon : ActionFilterAttribute,IMvcFilter
    {
        private IUser user = IoC.Resolve<IUser>();

        public MVCFilterAtrForLogon()
        {
            //表示作为action filter第一个执行
            this.Order = 0;
        }
        #region IMvcFilter Members

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            string msg = "此模块需要登录访问，请先登录";
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = msg
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "AccessDenied";
                filterContext.Controller.ViewData["deniedMsg"] = msg;
                filterContext.Result = ad;
            }
        }

        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //是否登录
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                this.RedirectToPage(filterContext);
                return;
            }

            var currentUser = filterContext.HttpContext.Session["userInfo"] as User;
            //如果用户信息为空，则跳转页面
            if (currentUser == null)
            {
                this.RedirectToPage(filterContext);
                return;
            }
        }
    }
}
